/**
 * 数据维护
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-01-20 09:34:53
 * @for 数据字典.html
 * @version $1.0$
 */
var BSTMG = BSTMG || {};
BSTMG.datadictionary = {
	init: function(){
		var that = this;
		//显示父类字典数据
		that.showStaticDataTypeList("","");
		//查询
		that.query();
		
		that.initSelectors();
		/* 表格全选 */
		that.tableCheckAll();
		/* 分类crud */
		that.categoryCRUD();
		/* 子分类crud */
		that.subcategoryCRUD();
	},
	//显示父类字典数据
	showStaticDataTypeList: function(staticDataCode,staticDataName){
		$.ajax({
				url: "/sysAdmin/staticData/staticDataTypeList?staticDataCode="+ staticDataCode +"&staticDataName="+staticDataName,
				type: 'post',
				dataType: 'json',
				success: function(data){
					var dataTypeList = data.dataTypeList;
					var $tbody = $("#dataTypeList tbody"),
		            	html = '';
			        if (dataTypeList.length > 0) {
			            for (var i = 0; i < dataTypeList.length; i++) {
			                var userInfo = dataTypeList[i];
			                html += '<tr>';
			                html += '<td><input type="checkbox" class="simple" data-id="'+userInfo.staticDataCode+'"></td>';
			                html += '<td>' + BSTMG.tools.checkNull(userInfo.staticDataCode) + '</td>';
			                html += '<td>' + BSTMG.tools.checkNull(userInfo.staticDataName) + '</td>';
			                html += '</tr>';
			            }
			            $tbody.html(html);
			        } else {
			            var $tr = '<tr class="nodata"><td colspan="3">暂无数据！</td></tr>';
			            $tbody.html($tr);
			        }
				},
				error: function(error){
					BSTYUN.dialog.warn("网络异常，请联系管理员！");
				}
			});
	},
	query : function(){
		$('#query').on('click',function(){
			var staticDataCode = $('#staticDataCode').val();
			var staticDataName = $('#staticDataName').val();
			BSTMG.datadictionary.showStaticDataTypeList(staticDataCode,staticDataName);
		})
	},
	initSelectors: function(){
		var that = this;
		that["query"] = {};
		that["query"]["#dataDicManager"] = $("#dataDicManager");
		// 左边
		that["query"][".leftpanel"] = $(".leftpanel");
		that["query"][".lfoperators"] = that["query"][".leftpanel"].find(".operators");
		that["query"]["#leftquery"] = $("#leftquery");
		// 右边
		that["query"][".rightpanel"] = $(".rightpanel");
		that["query"][".rgoperators"] = that["query"][".rightpanel"].find(".operators");
		// 表格
		that["query"][".bstable"] = $(".bstable");
	},
	tableCheckAll: function(){
		var that = this,
			$table = that["query"][".bstable"],
			$thead = $table.find("thead"),
			$tbody = $table.find("tbody");
		// 全选
		$thead.on("click",".simple",function(){
			var $this = $(this),
				$parent = $this.parents('table.table'),
				$checkbox = $parent.find('input[type=checkbox]').not($this);
			$this.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
			// 改变对应操作的可用性
			changeIsOperatot( $checkbox , $parent.hasClass("suptable") );
		});
		$tbody.on("click","input[type=checkbox]",function(){
			var $this = $(this),
				$parent = $this.parents('table.table'),
				$all = $parent.find("tbody input[type=checkbox]"),
				$checkbox = $all.not($this).filter(":checked");
			var $checkall = $parent.find("thead input.simple");
			( $this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false);
			// 改变对应操作的可用性
			changeIsOperatot( $all , $parent.hasClass("suptable") );
		});
		var $add_dictionary = $(".add_dictionary");
		function changeIsOperatot( $all , leftable ){
			var $op_check = $all.filter(":checked"),
				length = $op_check.length,
				$operator = $all.eq(0).parents(".bstable").prev(".operators"),
				$btn = $operator.find(".btn");
			if( length == 0 ){
				$btn.filter(".edit,.delete").addClass("disabled");
				leftable ? $add_dictionary.addClass("disabled") : null ;
			}else if( length == 1 ){
				$operator.find(".edit,.delete").removeClass("disabled");
				leftable ? $add_dictionary.removeClass("disabled") : null ;
			}else{
				$operator.find(".edit").addClass("disabled");
				$operator.find(".delete").removeClass("disabled");
				leftable ? $add_dictionary.addClass("disabled") : null ;
			};
		};
		// 更新右侧
		var $lftable = $table.eq(0),
			$rgoperator = $table.eq(1).prev(".operators");
		$lftable.on("click","input.simple",function(){
			var $lfcheckbox = $lftable.find("tbody input.simple");
			var $this = $(this),
				$checked = $lfcheckbox.filter(":checked") ,
				length = $checked.length;
			if( length == 1 ){ 
				// 更新右侧表格
				var id = $.trim( $checked.attr("data-id") );
				$.ajax({
	 				url: '/sysAdmin/staticData/staticDataList',
	 				type: 'post',
	 				dataType: 'json',
	 				data: { id: id } ,
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					// 循环data,插入数据
	 					var staticDataList = data.staticDataList;
						var $tbody = $table.eq(1).find("tbody").html( data ),
			            	html = '';
				        if (staticDataList.length > 0) {
				            for (var i = 0; i < staticDataList.length; i++) {
				                var staticDataInfo = staticDataList[i];
				                html += '<tr>';
				                html += '<td><input type="checkbox" class="simple" data-id1="'+staticDataInfo.staticDataCode+'"></td>';
				                html += '<td>' + staticDataInfo.staticDataCode + '</td>';
				                html += '<td>' + staticDataInfo.staticDataName + '</td>';
				                html += '<td>' + staticDataInfo.staticDataNum + '</td>';
				                html += '</tr>';
				            }
				            $tbody.html(html);
				        } else {
				            var $tr = '<tr class="nodata"><td colspan="4">暂无数据！</td></tr>';
				            $tbody.html($tr);
				        }
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
	 			});
			}else{
				// 清空右侧表格
				$table.eq(1).find("tbody").empty();
				$rgoperator.find(".edit,.delete").addClass("disabled");
			};
		});
	},
	categoryCRUD: function(){
		var that = this,
			$lfoperators = that["query"][".lfoperators"],
			$table = that["query"][".bstable"].eq(0),
			$lftbody = $table.find("tbody"),
			$rgtable = that["query"][".bstable"].eq(1),
			$rgtbody = $rgtable.find("tbody");
		$lfoperators.on("click",".addnew",function(){
			addNew();
		}).on("click",".edit",function(){
			var $checkbox = checkedCategory();
			if( $checkbox.length == 0 ){
				BSTYUN.dialog.warn("请选择一条记录！");
				return false;
			};
			editCategory( $checkbox );
		}).on("click",".delete",function(){
			var $checkbox = checkedCategory();
			if( $checkbox.length == 0 ){
				BSTYUN.dialog.warn("请选择一条记录！");
				return false;
			};
			deleteCategory( $checkbox );
		});
		// 查找选中的id
		function checkedCategory(){
			return  $table.find("tbody input.simple").filter(":checked");
		};
		// 新增
		function addNew( callback ){
			var dialog = null,
				html = '<div id="addnewcategory"><form class="form-horizontal" role="form"><div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">类型代码：</label><div class="col-sm-8"><input type="text" class="form-control" id="inputEmail3" placeholder="类型代码"></div></div><div class="form-group"><label for="inputPassword3" class="col-sm-4 control-label">类型名称：</label><div class="col-sm-8"><input type="text" class="form-control" id="inputPassword3" placeholder="类型名称"></div></div></form></div>';
			var _callback = callback ? callback() : null;
			var title = _callback ? _callback.title : "添加字典类型";
			dialog = BSTYUN.dialog.creat({
				id : "addnew",
				title: title,
				content : html,
				init: initaddNew
			});
			dialog.button(
				{
					name : "保存",
					callback : confirmAddNew
				},{
					name : "取消"
				}
			);
			function initaddNew(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control");
				if( _callback ){
					// 编辑时 填充内容
					$input.eq(0).attr("readonly",true);
					$input.eq(0).val( _callback.id );
					$input.eq(1).val( _callback.name );
				};
			};
			function confirmAddNew(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control");
				var staticDataCode = $.trim( $input.eq(0).val() ),
					staticDataName = $.trim( $input.eq(1).val() );
				if( staticDataCode == "" ){
					BSTYUN.dialog.warn("类型代码不能为空！");
					return false;
				};
				if( staticDataName == "" ){
					BSTYUN.dialog.warn("类型名称不能为空！");
					return false;
				};
				var datas ={
						staticDataCode: staticDataCode ,
						staticDataName: staticDataName
					};
				if( _callback ){
					// 有回调函数说明是编辑模式，update
					$.ajax({
		 				url: '/sysAdmin/operate/staticData/updateStaticData',
		 				type: 'post',
		 				dataType: 'json',
		 				data: datas ,
		 				success: function(data){
		 					if(data.isSuccess) {
		 						// 编辑时 修改内容
	 							$lftbody.find("tr").each(function(index,val){
	 								var $this = $(this),
	 									code = $.trim( $this.find("td").eq(1).text() );
	 								if( staticDataCode == code ){
	 									$this.find("td").eq(2).text( staticDataName );
	 								};
	 							});
		 					}else {
		 						BSTYUN.dialog.warn("信息保存失败，请重新编辑！");
		 					}
		 				},
		 				error: function(error){
		 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
		 				}
		 			});
				}else{
					// 无回调函数说明是新增模式，insert
					$.ajax({
		 				url: '/sysAdmin/operate/staticData/addStaticData',
		 				type: 'post',
		 				dataType: 'json',
		 				data: datas ,
		 				success: function(data){
		 					if(data.isSuccess) {
		 						//location.href="/sysAdmin/staticData/dataDicManager";
		 						// 新增是添加内容
		 						$lftbody.append('<tr><td><input type="checkbox" class="simple" data-id="' + staticDataCode + '"></td><td>' + staticDataCode + '</td><td>' + staticDataName + '</td></tr>');
		 					}else {
		 						BSTYUN.dialog.warn("类型代码已存在，请重新编辑！");
		 					}
		 				},
		 				error: function(error){
		 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
		 				}
		 			});
				};
			};
		};
		// 编辑分类
		function editCategory( $checkbox ){
			var $next = $checkbox.eq(0).parent().next(),
				id = $.trim( $next.text() ),
				name = $.trim( $next.next().text() );
			addNew(function(){
				return {
					id: id,
					name: name,
					title: "编辑字典类型"
				}
			});
		};
		// 删除
		function deleteCategory( $checkbox ){
			var ids = [];
			$checkbox.each(function(index,val){
				ids.push( $.trim( $(this).attr("data-id") ) );
			});
			BSTYUN.dialog.confirm("确定要删除选中项吗？",function(){
				$.ajax({
	 				url: '/sysAdmin/operate/staticData/deleteStaticData',
	 				type: 'post',
	 				dataType: 'json',
	 				data: { ids: ids.join(",")} ,
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isSuccess){
	 						location.href="/sysAdmin/staticData/dataDicManager";
	 						// 删除服务器成功删除的项目
//		 					$checkbox.each(function(index,val){
//		 						var $this = $(this);
//		 						$this.parent().parent().remove();
//		 					});
						}else {
							BSTYUN.dialog.warn(data.message);
						}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
	 			});
			});
		};
	},
	subcategoryCRUD: function(){
		var that = this,
			$rgoperators = that["query"][".rgoperators"],
			$table = that["query"][".bstable"].eq(1),
			$rgtable = $table.find("tbody") ;
		$rgoperators.on("click",".add_dictionary",function(){
			var $checkbox = that["query"][".bstable"].eq(0).find("tbody input:checked");
			if( $checkbox.length == 0 ){
				BSTYUN.dialog.warn("请选择一条记录！");
				return false;
			};
			addDictionary( $checkbox );
		}).on("click",".edit",function(){
			var $checkbox = checkedCategory();
			if( $checkbox.length == 0 ){
				BSTYUN.dialog.warn("请选择一条记录！");
				return false;
			};
			editCategory( $checkbox );
		}).on("click",".delete",function(){
			var $checkbox = checkedCategory();
			if( $checkbox.length == 0 ){
				BSTYUN.dialog.warn("请选择一条记录！");
				return false;
			};
			deleteCategory( $checkbox );
		});
		// 查找选中的id
		function checkedCategory(){
			return  $table.find("tbody input.simple").filter(":checked");
		};
		// 新增字典项
		function addDictionary( $checkbox ){
			var dialog = null,
				html = '<div id="addsubcategory"><form class="form-horizontal" role="form"><div class="form-group"><label for="inputEmail3" class="col-sm-5 control-label">上级类型代码：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputEmail3" placeholder="上级类型代码" readonly></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-5 control-label">字典项代码：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputEmail3" placeholder="字典项代码"></div></div><div class="form-group"><label for="inputPassword3" class="col-sm-5 control-label">字典项名称：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputPassword3" placeholder="字典项名称"></div></div><div class="form-group"><label for="inputEmail3" class="col-sm-5 control-label">排序编号：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputEmail3" placeholder="排序编号"></div></div></form></div>';
			dialog = BSTYUN.dialog.creat({
				id : "addsub",
				title: "新增字典项",
				content : html,
				init: initaddSub
			});
			dialog.button(
				{
					name : "保存",
					callback : confirmAddSub
				},{
					name : "取消"
				}
			);
			function initaddSub(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control"),
					id = $.trim( $checkbox.eq(0).parent().next().text() );
				$input.eq(0).val( id );
			};
			function confirmAddSub(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control");
				var parentCode = $.trim( $checkbox.eq(0).parent().next().text() ),
					staticDataCode = $.trim( $input.eq(1).val() ),
					staticDataName = $.trim( $input.eq(2).val() ),
					staticDataNum = $.trim( $input.eq(3).val() );
				if( staticDataCode == "" ){
					BSTYUN.dialog.warn("字典项代码不能为空！");
					return false;
				};
				if( staticDataName == "" ){
					BSTYUN.dialog.warn("字典项名称不能为空！");
					return false;
				};
				if( staticDataNum == "" ){
					BSTYUN.dialog.warn("排序编号不能为空！");
					return false;
				}else if( isNaN( staticDataNum ) ){
					BSTYUN.dialog.warn("排序编号必须为数字！");
					return false;
				};
				var datas ={
					parentCode: parentCode,
					staticDataCode: staticDataCode ,
					staticDataName: staticDataName,
					staticDataNum: staticDataNum
				};
				$.ajax({
	 				url: '/sysAdmin/operate/staticData/addStaticData',
	 				type: 'post',
	 				dataType: 'json',
	 				data: datas ,
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isSuccess) {
	 						var html = '<tr><td><input type="checkbox" class="simple" data-id1="' + staticDataCode + '"></td>';
	 							html += '<td>' + staticDataCode + '</td>';
	 							html += '<td>' + staticDataName + '</td>';
	 							html += '<td>' + staticDataNum + '</td></tr>';
	 						if( $rgtable.find("tr:first-child").hasClass("nodata") ){
	 							$rgtable.html( html );
	 							return ;
	 						};
	 						$rgtable.append( html );
	 					}else {
	 						BSTYUN.dialog.warn("类型代码已存在，请重新编辑！");
	 					}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
	 			});
			};
		};
		// 新增子类型
		function addNew( callback ){
			var dialog = null,
				html = '<div id="addnewsubcategory"><form class="form-horizontal" role="form"><div class="form-group"><label for="inputEmail3" class="col-sm-5 control-label">字典项代码：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputEmail3" placeholder="字典项代码"></div></div><div class="form-group"><label for="inputPassword3" class="col-sm-5 control-label">字典项名称：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputPassword3" placeholder="字典项名称"></div></div><div class="form-group"><label for="inputPassword3" class="col-sm-5 control-label">排序编号：</label><div class="col-sm-7"><input type="text" class="form-control" id="inputPassword3" placeholder="排序编号"></div></div></form></div>';
			var _callback = callback ? callback() : null;
			var title = _callback ? _callback.title : "添加子类型";
			dialog = BSTYUN.dialog.creat({
				id : "addnewsub",
				title: title,
				content : html,
				init: initaddNew
			});
			dialog.button(
				{
					name : "保存",
					callback : confirmAddNew
				},{
					name : "取消"
				}
			);
			function initaddNew(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control");
				if( _callback ){
					// 编辑时 填充内容
					$input.eq(0).attr("readonly",true);
					$input.eq(0).val( _callback.dicid );
					$input.eq(1).val( _callback.dicname );
					$input.eq(2).val( _callback.orderon );
				};
			};
			function confirmAddNew(){
				var $content = this.DOM.content,
					$input = $content.find("input.form-control");
				var staticDataCode = $.trim( $input.eq(0).val() ),
					staticDataName = $.trim( $input.eq(1).val() ),
					staticDataNum = $.trim( $input.eq(2).val() );
				if( staticDataCode == "" ){
					BSTYUN.dialog.warn("字典项代码不能为空！");
					return false;
				};
				if( staticDataName == "" ){
					BSTYUN.dialog.warn("字典项名称不能为空！");
					return false;
				};
				if( staticDataNum == "" ){
					BSTYUN.dialog.warn("排序编号不能为空！");
					return false;
				};

				var datas ={
					staticDataCode: staticDataCode,
					staticDataName: staticDataName,
					staticDataNum: staticDataNum
				};
				$.ajax({
	 				url: '/sysAdmin/operate/staticData/updateStaticData',
	 				type: 'post',
	 				dataType: 'json',
	 				data: datas ,
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isSuccess) {
	 						if( _callback ){
	 							// 有回调函数说明是编辑模式，update
	 							$rgtable.find("tr").each(function(index,val){
	 								var $this = $(this),
	 									code = $.trim( $this.find("td").eq(1).text() );
	 								if( staticDataCode == code ){
	 									var $td = $this.find("td");
	 									$td.eq(2).text( staticDataName );
	 									$td.eq(3).text( staticDataNum );
	 								};
	 							});
	 						}else{
	 							// 无回调函数说明是新增模式，insert
	 						};
	 					}else {
	 						BSTYUN.dialog.warn("信息保存失败，请重新编辑！");
	 					}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
	 			});
			};
		};
		// 编辑子类型
		function editCategory( $checkbox ){
			var $next = $checkbox.eq(0).parent().next(),
				dicid = $.trim( $next.text() ),
				dicname = $.trim( $next.next().text() ),
				orderon = $.trim( $next.next().next().text() );
			addNew(function(){
				return {
					//typeid: typeid,
					dicid: dicid,
					dicname: dicname,
					orderon: orderon,
					title: "编辑字典项"
				}
			});
		};
		// 删除
		function deleteCategory( $checkbox ){
			var ids = [];
			$checkbox.each(function(index,val){
				ids.push( $.trim( $(this).attr("data-id1") ) );
			});
			BSTYUN.dialog.confirm("确定要删除选中项吗？",function(){
				$.ajax({
	 				url: '/sysAdmin/operate/staticData/deleteStaticData',
	 				type: 'post',
	 				dataType: 'json',
	 				data: { ids: ids.join(",")} ,
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isSuccess) {
	 						// 删除服务器成功删除的项目
		 					$checkbox.each(function(index,val){
		 						var $this = $(this);
		 						$this.parent().parent().remove();
		 					});
	 					}else {
	 						BSTYUN.dialog.warn("删除失败！！");
	 					}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
	 			});
			});
		};
	}
};

$(function(){
	BSTMG.datadictionary.init();
});
//回车键查询功能
function keyQuery(){
	if(event.keyCode == 13){
		$('#query').trigger("click");
	}
}